package com.zhongpengcheng.blog.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 返回体工具类，封装{@link HttpServletResponse}相关操作
 *
 * @author zhongpengcheng
 * @date 2020-11-14 12:56:53
 * @version 1.0
*/
@Slf4j
public class ResponseUtils {

    private ResponseUtils() {
    }

    /**
     * 向返回体中写入数据
     * @param response HTTP Servlet响应
     * @param data 待写入数据
     * @param <T> 待写入数据泛型
     */
    public static <T> void write(HttpServletResponse response, @Nullable T data) {

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        try(PrintWriter writer = response.getWriter()) {
            writer.write(JSON.toJSONString(data));
            writer.flush();
        } catch (IOException e) {
            log.error("写入数据到response失败, data={}", data);
        }
    }
}
